#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011 BidiX (http://bidix.info)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
'''
	Wrapper for django template in GAE
'''
import os
import logging
import datetime

import config
from notewiki.model import Article
from notewiki.ui import dehtml

from django.conf import settings
from django.template import TemplateDoesNotExist, Context
from django.template.loader import BaseLoader
import django.template.loader

import webapp2

class WikiLoader(BaseLoader):
	"""
 		Loader for loading templates from wiki 
		with a fall-back to file

		add in django settings : 
		TEMPLATE_LOADERS=[('notewiki.ui.template.WikiLoader',)]

	"""
	is_usable = True
	
	def load_file_template_source(self, template_name):
		# try to load from file
		config = webapp2.get_app().config
		file_path = config.get('file_template_root_path') + '/' + template_name + '.djhtml'
		try:
			file = open(file_path)
			try:
				return (file.read().decode(config.get('file_charset')), file_path)
			finally:
				file.close()
		except IOError:
			error_msg = "Template file %s not found"%file_path
			logging.error(error_msg)
			raise TemplateDoesNotExist(error_msg)

	def load_wiki_template_source(self, template_name):
			config = webapp2.get_app().config
			wiki_template_root_folder = config.get('wiki_template_root_folder')
			article = Article.get_by_name(wiki_template_root_folder+'/'+template_name)
			if article:
				logging.debug("Render with article %s"%wiki_template_root_folder+'/'+template_name)
				return (article.text, template_name)
			else:
				return(self.load_file_template_source(template_name))
			
	def load_template_source(self, template_name, template_dirs=None):
		if webapp2.get_app().config.get('wiki_template_support'):
			return self.load_wiki_template_source(template_name)
		else:
			return self.load_file_template_source(template_name)
		
	load_template_source.is_usable = True

def truncatechars(str, maxlength=10):
	"""
		django template filter : truncate maxlength chars
	"""
	m = int(maxlength)
	if len(str) <= m:
		return str
	else:
		return str[0:m-4]+'...'
	
def ltruncatechars(str, maxlength=10):
	"""
		django template filter : left truncate maxlength chars
	"""
	m = int(maxlength)
	if len(str) <= m:
		return str
	else:
		return '...'+str[(len(str)-m)+4:]

django.template.defaultfilters.register.filter('truncatechars', truncatechars)
django.template.defaultfilters.register.filter('ltruncatechars', ltruncatechars)

def render(template_path, template_context, debug=False):
	os.environ['DJANGO_SETTINGS_MODULE'] = 'notewiki.ui.django_settings'
	template_context['current_year'] = datetime.datetime.utcnow().strftime('%Y')
	if template_context.has_key('title'):
			template_context['html_title'] = dehtml(template_context['title'])
	t, name = django.template.loader.find_template(template_path)
	return t.render(Context(template_context))
